<?php
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/26 0026
 * Time: 14:35
 */

namespace HiCommon\Service;

use HiCommon\MongodbModel\MongoPhoneCodeLog;
use HiCommon\Repository\UsersRepository;

class WxLoginService extends BaseService
{
    static private $wx_appid = 'wx20566816a0372a67';

    static private $wx_appsecret = 'fbcbad0bd35981b2e476701fc20930a7';

    /*获取access token 有效期2小时*/
    public function get_access_token($s_code){
        $s_wx_appid     = self::$wx_appid;
        $s_wx_appsecret     = self::$wx_appsecret;
        
        /* 获取token */
        $s_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$s_wx_appid.'&secret='.$s_wx_appsecret.'&code='.$s_code.'&grant_type=authorization_code';
        $ch          = curl_init();
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch,CURLOPT_URL,$s_token_url);
        $json_token = curl_exec($ch);
        curl_close($ch);
        $arr_token = json_decode($json_token,true);
        
        return $arr_token;
    }

    /*刷新token 有效期为30天*/
    public function refresh_token($s_refresh_token){
        $s_wx_appid     = self::$wx_appid;

        /* 刷新token 有效期为30天 */
        $s_refresh_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$s_wx_appid.'&grant_type=refresh_token&refresh_token='.$s_refresh_token
          .'';
        $ch                  = curl_init();
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch,CURLOPT_URL,$s_refresh_token_url);
        $json_refresh_token = curl_exec($ch);
        curl_close($ch);

        $arr_refresh_token = json_decode($json_refresh_token,true);

        return $arr_refresh_token;
    }

    /*获取用户信息*/
    public function get_wx_user($s_access_token = '',$s_openid = ''){
        $s_userinfo_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$s_access_token.'&openid='.$s_openid.'&lang=zh_CN';
        $ch             = curl_init();
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch,CURLOPT_URL,$s_userinfo_url);
        $json_userinfo = curl_exec($ch);
        curl_close($ch);
        $arr_wxuser = json_decode($json_userinfo,true);
        return $arr_wxuser;
    }

    /*强制获取用户信息*/
    public function force_wx_user($s_code){
        /*获取access token*/
        $arr_token_data = $result = self::get_access_token($s_code);
        $s_errcode = $result['errcode'];
        if($s_errcode > 0){
            $s_errmsg = $result['errmsg'];
            return hello_error('微信登录失败',[],'获取access token:'.$s_errmsg);
        }

        //获取用户信息
        $s_access_token = $result['access_token'];
        $s_openid = $result['openid'];
        $result = self::get_wx_user($s_access_token,$s_openid);
        $s_errcode = $result['errcode'];
        if($s_errcode > 0){
            $s_errmsg = $result['errmsg'];
            return hello_error('微信登录失败',[],'获取用户个人信息:'.$s_errmsg);
        }

        $result['token_data'] = $arr_token_data;
        return  hello_success('成功',$result);

    }

    /*微信登录*/
    public function api_app_wechat_login($arr_wxuser,$s_unique_token = ''){
        $s_unionid = $arr_wxuser['unionid'];
        $arr_where = ['unionid'=>$s_unionid];
        $arr_option = [
          'field'=>['id','username','nickname','wx_nickname','head_img','pass','phone','unionid','small_openid','app_openid','status']
        ];
        $arr_user = UsersRepository::base_get_one($arr_where,$arr_option);
        $n_is_bind_phone = 2;
        if(is_null($arr_user)) {
            // 记录微信等到用户提交手机号后才去注册账号
            $arr_user = [
              'id'=>0,
              'username'=>'',
              'nickname'=>$arr_wxuser['nickname'],
              'wx_nickname'=>$arr_wxuser['nickname'],
              'head_img'=>$arr_wxuser['head_img'],
              'pass'=>'',
              'phone'=>'',
              'unionid'=>$arr_wxuser['unionid'],
              'small_openid'=>'',
              'app_openid'=>$arr_wxuser['app_openid'],
              'status'=>1,
            ];
            $arr_data['user'] = $arr_user;
            $arr_data['is_bind_phone'] = $n_is_bind_phone;

            return  hello_success('微信登录成功',$arr_data);
        }
        else {
            //已注册用户 分2类 1-已绑定手机号 2-未绑定手机号
            $arr_user_data = $arr_user->toarray();
//            $n_id = $arr_user_data['id'];
//            $s_app_openid = $arr_wxuser['app_openid'];
//            $s_small_openid = $arr_wxuser['small_openid'];

//            /*绑定微信app*/
//            if(empty($arr_user_data['app_openid'])){
//                //绑定微信app
//                $arr_data = ['id'=>$n_id,'app_openid'=>$s_app_openid];
//                $res = UsersRepository::base_edit_one($arr_data);
//                if($res === false){
//                    return hello_error('微信登录失败',[],'绑定微信app失败');
//                }
//            }

            //更新微信openid
            $s_app_openid = $arr_wxuser['app_openid'];
            $arr_data = [
              'id'=>$arr_user_data['id'],
              'app_openid'=>$s_app_openid,
            ];
            $result = UsersRepository::base_edit_one($arr_data);
            if($result === false){
                return hello_error('登录失败',[],'小程序openid修改失败');
            }

            if(empty($arr_user_data['phone'])){
                //2-未绑定手机号
                $arr_user_data['head_img'] = $arr_user_data['head_img']['full_src'];
                $arr_data = ['user'=>$arr_user_data];
                $arr_data['is_bind_phone'] = $n_is_bind_phone;
                return  hello_success('微信登录成功',$arr_data);
            }
            else{
                //1-已绑定手机号 用户登录
                $arr_input = [
                  'username' => str_trim($arr_user_data['username']),
                  'password' => str_trim($arr_user_data['pass']),
                ];

                //登录操作
                $result = LoginUserService::app_attempt($arr_input);
                $result['data']['is_bind_phone'] = 1;
                return $result;
            }

        }
    }
    

    /*微信登录*/
    public function api_wechat_login($s_code){
        if(mb_strlen($s_code) <= 0){
            return hello_error('微信登录失败',[],'请先获取code');
        }

        /*获取微信用户信息*/
        $result = self::force_wx_user($s_code);
        $arr_wxuser = $result['data'];
        if($result['state'] != 0){
            return $result;
        }

        /*微信登录*/
        $arr_wxuser = [
          'unionid'=>$arr_wxuser['unionid'],
          'app_openid'=>$arr_wxuser['openid'],
          'nickname'=>$arr_wxuser['nickname'],
          'head_img'=>$arr_wxuser['headimgurl'],
          'sex'=>$arr_wxuser['sex'],
          'country'=>$arr_wxuser['country'],
          'province'=>$arr_wxuser['province'],
          'city'=>$arr_wxuser['city'],
          'language'=>$arr_wxuser['language'],
        ];

        $result = self::api_app_wechat_login($arr_wxuser);
        return $result;
    }


    /*微信登录绑定手机号*/
    public function api_wechat_bind_phone($arr_input = []){
        //微信APP注册用户，不会携带参数，邀请无效
        filter_input_data($arr_input);
        if(mb_strlen($arr_input['phone']) != 11){
            return hello_error('请填写11位手机号');
        }
        if(mb_strlen($arr_input['code']) != 6){
            return hello_error('请填写6位验证码');
        }
        if(mb_strlen($arr_input['nickname']) <= 0){
            return hello_error('请输入微信昵称');
        }

        if(mb_strlen($arr_input['head_img']) <= 0){
            return hello_error('请输入微信头像');
        }

        if(mb_strlen($arr_input['unionid']) <= 0){
            return hello_error('请输入unionid');
        }

        if(mb_strlen($arr_input['app_openid']) <= 0){
            return hello_error('请输入微信openid');
        }


        //验证手机号
        $s_phone = $arr_input['phone'];
        $s_code = $arr_input['code'];
        $arr_where = ['phone'=>$arr_input['phone']];
        $arr_option = ['field'=>['id','phone','status']];
        $result = UsersRepository::base_get_one($arr_where,$arr_option);
        if(!is_null($result)){
            return hello_error('手机号已被注册');
        }

        //根据微信信息和手机号注册账号-如果是小程序账号，修改信息即可
        $n_id = intval($arr_input['id']);
//        $s_unique_token = str_trim($arr_input['unique_token']);
        unset($arr_input['code']);
//        unset($arr_input['unique_token']);
        if($n_id <= 0){
            //新号，直接注册
            unset($arr_input['id']);
            $result = LoginUserService::api_register_user($arr_input);
            if($result['state'] != 0){
                return $result;
            }

        }
        else {
            //已有账户，修改
            $result = UsersRepository::base_edit_one($arr_input);
            if($result === false){
                return hello_error('登录失败');
            }

        }

        //用户登录
        $result = LoginUserService::app_phonecode_login_direct($s_phone,$s_code);
        if($result['state'] != 0){
            return $result;
        }
        return  $result;

    }

    /*绑定微信app*/
    public function api_bind_wechat_app($n_uid = 0,$s_code = ''){
        $n_uid = intval($n_uid);
        $s_code = str_trim($s_code);
        if($n_uid <= 0){
            return hello_error('用户id不能为空');
        }
        if(mb_strlen($s_code) <= 0){
            return hello_error('微信登录失败',[],'请先获取code');
        }

        /*获取微信用户信息*/
        $result = self::force_wx_user($s_code);
        $arr_wxuser = $result['data'];
        if($result['state'] != 0){
            return $result;
        }

        //如果该微信已经被绑定 则不能继续绑定
        $arr_orwhere = [
          'unionid'=>$arr_wxuser['unionid'],
//          'app_openid'=>$arr_wxuser['openid'],
        ];
        $res = UsersRepository::base_get_all_orwhere($arr_orwhere)->toarray();
        if(count($res) == 1){
            if($res[0]['id'] != $n_uid){
                return hello_error('绑定微信失败',[],'微信号已被绑定，请选择其他微信号');
            }
        }
        elseif(count($res) > 1){
            return hello_error('绑定微信失败',[],'微信号绑定异常，请联系管理员');

        }

        $arr_data = [
          'id'=>$n_uid,
          'unionid'=>$arr_wxuser['unionid'],
          'wx_nickname'=>$arr_wxuser['nickname'],
//          'app_openid'=>$arr_wxuser['openid'],
        ];
        $result = UsersRepository::base_edit_one($arr_data);
        if($result === false){
            return hello_error('绑定微信失败');
        }
        return  hello_success('绑定微信成功');

    }

    /*解绑微信*/
    public function api_unbind_wechat_app($n_uid = 0){
        $n_uid = intval($n_uid);
        if($n_uid <= 0){
            return hello_error('用户id不能为空');
        }

        //解绑微信
        $arr_data = [
          'id'=>$n_uid,
          'unionid'=>'',
          'wx_nickname'=>'',
        ];
        $result = UsersRepository::base_edit_one($arr_data);
        if($result === false){
            return hello_error('解绑微信失败');
        }
        return  hello_success('解绑微信成功');

    }



    /*微信登录绑定手机号*/
    public function api_wx_login_bind_phone($arr_input = []){

        filter_input_data($arr_input);
        if(mb_strlen($arr_input['phone']) != 11){
            return hello_error('请填写11位手机号');
        }
        if(mb_strlen($arr_input['code']) != 6){
            return hello_error('请填写6位验证码');
        }
        if(mb_strlen($arr_input['nickname']) <= 0){
            return hello_error('请输入微信昵称');
        }
        if(mb_strlen($arr_input['head_img']) <= 0){
            return hello_error('请输入微信头像');
        }
        if(mb_strlen($arr_input['unionid']) <= 0){
            return hello_error('请输入unionid');
        }

        //验证手机验证码
        $s_phone = $arr_input['phone'];
        $s_code = $arr_input['code'];
        $result = check_phone_code($s_phone,$s_code);
        if($result['state'] != 0){
            return $result;
        }

        //验证手机号是否被注册
        $arr_where = ['phone'=>$arr_input['phone']];
        $arr_option = ['field'=>['id','phone','status']];
        $result = UsersRepository::base_get_one($arr_where,$arr_option);
        if(!is_null($result)){
            return hello_error('手机号已被注册');
        }

        //邀请者ID
        $s_unique_token = str_trim($arr_input['unique_token']);
        $arr_where = ['unique_token'=>$s_unique_token];
        $arr_option = ['field'=>['id']];
        $n_invite_id = intval(UsersRepository::base_get_one($arr_where,$arr_option)->id);

        //根据微信信息和手机号注册账号 新号，直接注册
        $arr_remain = ['phone','nickname','head_img','unionid','small_openid','app_openid'];
        $arr_input = array_remain($arr_input,$arr_remain);
        $result = LoginUserService::api_register_user($arr_input,$n_invite_id);
        if($result['state'] != 0){
            return $result;
        }

        $s_username = $result['data']['user']['username'];
        $s_pass = $result['data']['user']['pass'];

        //登录操作
        $arr_input = [
          'username' => str_trim($s_username),
          'password' => str_trim($s_pass)
        ];
        $result = LoginUserService::app_attempt($arr_input);
        if ($result['state'] != 0) {
            //登录失败
            return $result;
        }
        else{
            //登录成功 销毁已使用的手机验证码
            unset_redis_phone_code($s_phone);
            return  $result;
        }
    }

}